package dbms.ypr;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

//工具类
public class Utils {

    /**
     * 表名解析
     */
    private static Pattern p = Pattern.compile("\\s+from\\s+(\\w+)(\\s+|,|;)(\\w*)|\\s+join\\s+(\\w+)\\s+(\\w*)\\s+on", Pattern.CASE_INSENSITIVE);

    //获取所有数据库名称,查看路径下所有文件夹
    public static List<String> getAllDatabase(String path) {
        List<String> list = new ArrayList<>();
        File file = new File(path);
        File[] fileList = file.listFiles();
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isDirectory()) {
                list.add(fileList[i].getName());
            }
        }
        return list;
    }


    //判断输入语句的括号是否匹配
    public static boolean bracketMatch(String sql) {

        Stack<String> stack = new Stack<>();


        char[] chars = sql.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(') {
                stack.push("(");
            } else if (chars[i] == ')') {
                if (stack.empty()) {
                    return false;
                } else {
                    stack.pop();
                }
            }
        }
        return true;
    }


    //获取当前数据库下的所有表
    public static List<String> getAllTables(String nowPath) {
        List<String> list = new ArrayList<>();
        File file = new File(nowPath);
        File[] fileList = file.listFiles();
        if (fileList != null) {
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile()) {
                    String name = fileList[i].getName();
                    int index = name.lastIndexOf(".");
                    String tableName = name.substring(0, index);
                    list.add(tableName);
                }
            }
        } else {

        }
        return list;
    }

    /**
     * 预处理sql
     *
     * @param sql sql
     * @return 处理后sql
     * @throws Exception 异常
     */
    private static String preHandleSql(String sql, boolean removeBrackets) throws Exception {
        // 1. 统一换行符
        if (sql.contains("\r\n")) {
            sql = sql.replaceAll("\r\n", "\n");
        } else {
            sql = sql.replaceAll("\r", "\n");
        }
        // 2. 去掉注释
        String[] rows = sql.split("\n");
        StringBuilder sb = new StringBuilder(sql.length());
        for (String row : rows) {
            int indexOfComment = row.indexOf("--");
            if (indexOfComment == -1) {
                sb.append(row).append("\n");
            } else {
                sb.append(row, 0, indexOfComment).append("\n");
            }
        }
        if (removeBrackets) {
            sql = removeBrackets(sb);
        }
        // 4. 找到第一个select和from，其间的字段即是要查询的字段列表
        return sql.toLowerCase();

    }

    /**
     * 括号消除：消除括号和括号中包含的内容，非贪心模式
     * <p>
     * 例如：
     * <p>
     * 输入select (ssss(sadf)sdfsdf(sdssf(sssdf)dsssf)dsslf) as a, (asdfsdf) as b, (asdfsdf) as c from dsfdf
     * <p>
     * a组 b组 a组 c组 d组 b组 c组 d组 m组 m组 x组 x组
     * <p>
     * A组 A组 B组 B组 C组 C组
     * <p>
     * 去掉select (去 掉 部 分) as a, (去掉部分) as b, (去掉部分) as c from dsfdf
     * <p>
     * 输出select as a, as b, as c from dsfdf
     *
     * @param str 消除前的字符串
     * @return 消除后的字符串
     * @throws Exception 括号不匹配
     */
    private static String removeBrackets(StringBuilder str) throws Exception {
        // 1. 收集括号组
        List<int[]> bracketsContainer = new ArrayList<>();
        collectBrackets(str, 0, bracketsContainer);
        if (bracketsContainer.isEmpty()) {
            return str.toString();
        }

        // 2. 消除括号组
        StringBuilder newStr = new StringBuilder(str.length());
        int groupSize = bracketsContainer.size();
        for (int i = 0; i < groupSize; i++) {
            int[] currentBrackets = bracketsContainer.get(i);
            if (i == 0) {
                // 刚到第一组
                newStr.append(str.subSequence(0, currentBrackets[0]));
            }
            if (i + 1 == groupSize) {
                // 已到最后一组
                newStr.append(str.subSequence(currentBrackets[1] + 1, str.length()));
            } else {
                // 未到最后一组
                int[] nextBrackets = bracketsContainer.get(i + 1);
                newStr.append(str.subSequence(currentBrackets[1] + 1, nextBrackets[0]));
            }

        }

        return newStr.toString();

    }

    /**
     * 收集括号组
     *
     * @param str               消除前的字符串
     * @param fromIndex         从哪开始找括号
     * @param bracketsContainer 括号组容器
     * @throws Exception 括号不匹配、括号嵌套层级过多
     */
    private static void collectBrackets(StringBuilder str, int fromIndex, List bracketsContainer) throws Exception {
        int firstLeftBracket = str.indexOf("(", fromIndex + 1);
        int nextLeftBracket = firstLeftBracket;
        // SQL中不包含左括号时，直接返回
        if (firstLeftBracket == -1) {
            return;
        }
        // 括号层级(因为前面已经找到一个左括号，所以初始值为1)
        int level = 1;
        int nextRightBracket = str.indexOf(")", fromIndex + 1);
        if (nextRightBracket == -1) {
            throw new Exception("括号不匹配");
        }
        // 避免死循环
        int maxLevel = 1000;
        do {
            int tempLeftBracket = str.indexOf("(", nextLeftBracket + 1);
            if (tempLeftBracket == -1 || tempLeftBracket > nextRightBracket) {
                // 找不到下一个左括号或者下一个左括号已属于下一个括号组
                break;
            } else {
                nextLeftBracket = tempLeftBracket;
            }
            nextRightBracket = str.indexOf(")", nextRightBracket + 1);
            if (nextRightBracket == -1) {
                throw new Exception("括号不匹配");
            }
            level++;
        } while (level <= maxLevel);
        if (level >= maxLevel) {
            throw new Exception("括号嵌套层级过多");
        }
        // 把收集到的括号组放入容器
        bracketsContainer.add(new int[]{firstLeftBracket, nextRightBracket});
        // 递归
        collectBrackets(str, nextRightBracket, bracketsContainer);

    }

    /**
     * 解析sql中的表名
     *
     * @param sql sql
     * @return 表名
     * @throws Exception 异常
     */
    public static List<String> parseSqlRefTables(String sql) throws Exception {
        List<String> tableNames = new ArrayList<String>();
        String newSql = preHandleSql(sql, false).replaceAll("\n", " ");
        Matcher m = p.matcher(newSql);
        while (m.find()) {
            tableNames.add(m.group());
        }
        tableNames = tableNames.stream().map(a -> {
            a = a.trim();
            if (a.contains(";"))
                a = a.replace(";", "");
            return a;
        }).collect(Collectors.toList());
        List<String> result = new ArrayList<String>();
        for (String tableName : tableNames) {
            String trimTableName = tableName.split(" ")[1].trim();
            if (trimTableName.contains(",")) {
                result.addAll(Arrays.asList(trimTableName.split(",")));
            } else {
                result.add(trimTableName);
            }
        }
        return result.parallelStream().distinct().collect(Collectors.toList());

    }

//    public static void main(String[] args) throws Exception {
//        String data1 = "select * from aa a left join bb b on a.a=b.a;";
//        List tableNames = parseSqlRefTables(data1);
//
//        tableNames.forEach(System.out::println);
//
//    }
}
